package com.itheima.servlet;

import com.itheima.bean.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/userRegister")
public class UserRegister extends HttpServlet {
    //用户注册
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("txt/html;charset=utf-8");
        //判断验证码是否输入正确  在注册页面验证码图片生成时将验证码用session存起来了了
        String checkCode = (String) req.getSession().getAttribute("checkCode");
        //将用户输入的验证码拿出来
        String userCode = req.getParameter("checkCode");
        //比较严重
        if(!userCode.equalsIgnoreCase(checkCode)){
            //验证码输入错误返回  验证码不区分大小写
            //在注册页面显示验证码输入错误
            req.setAttribute("error","严重码输入有误!");
            req.getRequestDispatcher("register.jsp").forward(req,resp);
            return;
        }


        //获取用户输入的信息
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user);
        PrintWriter writer = resp.getWriter();
        //调用业务层的注册方法
        Boolean register = userService.register(user);
        if(register){
            //注册成功 弹窗注册成功
            writer.println("<script>");
            writer.println("alert('注册成功!');");
            writer.println("</script>");
            //转发到登录页面
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else {
            //注册失败 转发回注册页面  在注册页面显示   用户名已存在注册失败!
            /*writer.println("<script>");
            writer.println("alert('用户名已存在!注册失败!');");
            writer.println("</script>");*/
            req.setAttribute("error","用户名已存在!");
            req.getRequestDispatcher("register.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
